import socket
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread


# ================= UDP 服务部分 =================
def udp_open_server():
    UDP_IP = "0.0.0.0"
    UDP_PORT = 99

    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((UDP_IP, UDP_PORT))
    print(f"UDP服务已启动，监听端口: {UDP_PORT}")

    while True:
        # 接收数据（缓冲区大小为1024字节）
        data, addr = sock.recvfrom(1024)
        print(f"\n收到UDP消息 [{addr[0]}:{addr[1]}] -> {data.decode()}")

        # 发送响应（可选）
        response = f"已收到 {len(data)} 字节数据".encode()
        sock.sendto(response, addr)

def udp_shutdown_server():
    UDP_IP = "0.0.0.0"
    UDP_PORT = 17679

    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind((UDP_IP, UDP_PORT))
    print(f"UDP服务已启动，监听端口: {UDP_PORT}")

    while True:
        # 接收数据（缓冲区大小为1024字节）
        data, addr = sock.recvfrom(1024)
        print(f"\n收到UDP消息 [{addr[0]}:{addr[1]}] -> {data.decode()}")

        # 发送响应（可选）
        response = f"已收到 {len(data)} 字节数据".encode()
        sock.sendto(response, addr)


# ================= HTTP 服务部分 =================
class MyHTTPHandler(BaseHTTPRequestHandler):
    # 处理GET请求
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        response = f"HTTP服务已收到GET请求\n路径：{self.path}\n"
        self.wfile.write(response.encode())

    # 处理POST请求
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)

        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        response = f"HTTP服务已收到POST数据：{post_data.decode()}\n"
        self.wfile.write(response.encode())


def http_server():
    HTTP_IP = "0.0.0.0"
    HTTP_PORT = 8000

    server = HTTPServer((HTTP_IP, HTTP_PORT), MyHTTPHandler)
    print(f"HTTP服务已启动，监听端口: {HTTP_PORT}")
    server.serve_forever()


# ================= 主程序 =================
if __name__ == "__main__":
    # 启动UDP服务线程
    udp_open_thread = Thread(target=udp_open_server)
    udp_open_thread.daemon = True  # 设置为守护线程

    # 启动UDP服务线程
    udp_shutdown_thread = Thread(target=udp_shutdown_server)
    udp_shutdown_thread.daemon = True  # 设置为守护线程

    # 启动HTTP服务线程
    http_thread = Thread(target=http_server)
    http_thread.daemon = True

    # 启动线程
    udp_open_thread.start()
    udp_shutdown_thread.start()
    http_thread.start()

    try:
        # 保持主线程运行
        while True:
            pass
    except KeyboardInterrupt:
        print("\n服务已停止")
